package com.echo.code.thread;

import com.echo.code.thread.future.Future;
import com.echo.code.thread.future.service.FutureService;
import com.echo.code.thread.future.service.impl.FutureServiceImpl;
import java.util.concurrent.TimeUnit;
import org.junit.Test;

/**
 * Created by baiyap on 2018/7/20
 */
public class FutureTestCase {

  public static void main(String[] args) throws InterruptedException {
    // futureWithoutResultTestCase();
    futureTestCase();
    // futureCallbackTestCase();
  }

  @Test
  public static void futureWithoutResultTestCase() throws InterruptedException {
    FutureService<String, Integer> service = new FutureServiceImpl<>();
    Future<?> future = service.submit(() -> {
      sleep(40);
    });
    System.out.println(future.get() == null);
  }

  @Test
  public static void futureTestCase() throws InterruptedException {
    FutureService<String, Integer> service = new FutureServiceImpl<>();
    Future<Integer> future = service.submit(input -> {
      sleep(40);
      return input.length();
    }, "Hello");
    System.out.println(future.get());
  }

  @Test
  public static void futureCallbackTestCase() throws InterruptedException {
    FutureService<String, Integer> service = new FutureServiceImpl<>();
    Future<Integer> future = service.submit(input -> {
      sleep(40);
      return input.length();
    }, "hello", System.out::println);
  }


  public static void sleep(int sec) {
    try {
      TimeUnit.SECONDS.sleep(sec);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}